const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');

const app = express();
app.use(cors());
const port = 3000;

// MySQL连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'admin',
  database: 'easy_money_db',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

// 创建连接池
const pool = mysql.createPool(dbConfig);

// 获取股票推荐数据API
app.get('/api/recommendations', async (req, res) => {
  const startTime = new Date();
  console.log(`[${startTime.toISOString()}] 收到API请求`, {
    path: req.path,
    query: req.query,
    ip: req.ip
  });

  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    console.log(`查询参数: page=${page}, limit=${limit}, offset=${offset}`);

    const connection = await pool.getConnection();
    const [rows] = await connection.query(
      `SELECT 
        stock_code, 
        stock_name, 
        stock_price, 
        pe_ttm,
        frequency as recommendation_count,
        DATE_FORMAT(updated_at, '%Y-%m-%d') as update_date
      FROM investment_recommendation
      ORDER BY updated_at DESC
      LIMIT ? OFFSET ?`,
      [limit, offset]
    );
    connection.release();

    console.log(`查询成功，返回${rows.length}条记录`);
    res.json(rows);
  } catch (error) {
    const errorTime = new Date();
    console.error(`[${errorTime.toISOString()}] API请求失败`, {
      error: error.message,
      stack: error.stack
    });
    res.status(500).json({ error: 'Internal server error' });
  } finally {
    const endTime = new Date();
    const duration = endTime - startTime;
    console.log(`[${endTime.toISOString()}] 请求处理完成，耗时${duration}ms`);
  }
});

app.listen(port, () => {
  console.log(`API server running at http://localhost:${port}`);
});
